'use strict';

exports.main = async (event, context) => {
  console.log('=== markChatMessageRead 云函数开始 ===')
  console.log('1. 接收参数:', event)
  
  const db = uniCloud.database();
  const { partnerId, userId } = event;

  if (!partnerId || !userId) {
    console.log('❌ 缺少必要参数:', { partnerId, userId })
    return {
      code: 400,
      msg: '缺少必要参数'
    };
  }

  try {
    console.log('2. 标记与用户的聊天消息为已读...')
    
    // 查询所有未读的聊天消息
    const messagesRes = await db.collection('chatMessages')
      .where({
        receiverId: userId,
        senderId: partnerId,
        status: { $ne: 'read' }
      })
      .get();
    
    console.log('3. 找到未读消息数量:', messagesRes.data.length)
    
    if (messagesRes.data.length === 0) {
      console.log('✅ 没有未读消息')
      return {
        code: 200,
        msg: '没有未读消息',
        data: { updatedCount: 0 }
      };
    }
    
    // 批量更新消息为已读状态
    const messageIds = messagesRes.data.map(msg => msg._id);
    const result = await db.collection('chatMessages')
      .where({
        _id: db.command.in(messageIds)
      })
      .update({
        status: 'read',
        readTime: new Date()
      });
    
    console.log('4. 更新结果:', result)
    console.log('✅ 聊天消息标记为已读成功，共更新', result.updated, '条消息')

    return {
      code: 200,
      msg: '聊天消息已标记为已读',
      data: { 
        updatedCount: result.updated,
        messageIds: messageIds
      }
    };
  } catch (error) {
    console.error('❌ 标记聊天消息失败:', error);
    return {
      code: 500,
      msg: '标记聊天消息失败',
      error: error.message
    };
  }
};